package botcraft.server;

import java.io.PrintWriter;
import java.util.concurrent.BlockingQueue;
import java.util.logging.Logger;

public class Sender implements Runnable {
	private static final Logger logger = Logger.getLogger(Sender.class.getName());
	
	private final Worker worker;
	private final BlockingQueue<String> outputQueue;
	private final PrintWriter output;
	
	public Sender(final Worker worker, final BlockingQueue<String> outputQueue, final PrintWriter output) {
		this.worker = worker;
		this.outputQueue = outputQueue;
		this.output = output;
	}
	
	@Override
	public void run() {
		while (!Thread.interrupted()) {
			try {
				final String command = outputQueue.take();
				if (command == null)
					Thread.currentThread().getThreadGroup().interrupt();
				else {
					output.println(command);
					output.flush();
					if (output.checkError()) {
						logger.warning("Error sending command " + command + " to " + worker);
						Thread.currentThread().getThreadGroup().interrupt();
					}
				}
			} catch (InterruptedException e) {
				return;
			}
		}
	}
}
